<?php
/**
 * 项目启动引导
 * 
 */

require_once ('Zend/Loader/Autoloader.php');

// 包含项目公共文件库
require_once (LIB_PATH . 'Cms/Global.php');

$autoloader = Zend_Loader_Autoloader::getInstance ();
$autoloader->registerNamespace ( 'Cms_' );
$autoloader->registerNamespace ( 'DB_' );
$autoloader->registerNamespace ( 'Model_' );

class ApplicationBootstrap {
	public static $frontController = null;
	public static $root = '';
	public static $registry = null;
	public static $application = '';
	
	public function __construct($_application) {
		switch ($_application) {
			case 'www' :
				self::$application = $_application;
				define ( 'APP_PATH', APP_ROOT_PATH . $_application . DIRECTORY_SEPARATOR );
				define ( 'APP_CACHE_PATH', APP_PATH . 'Cache' . DIRECTORY_SEPARATOR );
				break;
			case 'admin' :
				self::$application = $_application;
				define ( 'APP_PATH', APP_ROOT_PATH . $_application . DIRECTORY_SEPARATOR );
				define ( 'APP_CACHE_PATH', APP_PATH . 'Cache' . DIRECTORY_SEPARATOR );
				
				// 定义数据库备份目录
				define ( 'APP_DATABASES_PATH', DATA_PATH . 'Databases' . DIRECTORY_SEPARATOR );
				break;
			case 'api' :
				self::$application = $_application;
				define ( 'APP_PATH', APP_ROOT_PATH . $_application . DIRECTORY_SEPARATOR );
				define ( 'APP_CACHE_PATH', APP_PATH . 'Cache' . DIRECTORY_SEPARATOR );
				break;
			default :
				
				break;
		}
		
		// 定义上传目录
		define ( 'UPLOAD_PATH', ROOT_DIR . 'Public' . DIRECTORY_SEPARATOR . 'www' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR );
		
		self::setupRegistry ();
		self::setupConfig ();
		self::setupDateTime ();
		self::setupFrontController ();
		self::setupView ();
		self::setupDatabase ();
		// self::setupMemcache ();
		self::setupSession ();
		self::setupCache ();
	}
	
	/**
	 * 设置注册
	 */
	public static function setupRegistry() {
		self::$registry = new Zend_Registry ();
		Zend_Registry::setInstance ( self::$registry );
	}
	
	/**
	 * 设置配置文件
	 */
	public static function setupConfig() {
		// 控制器视图配置文件
		$application_config = new Zend_Config_Ini ( APP_PATH . 'config.ini', null, array ('allowModifications' => 1 ) );
		
		// 网站整体配置文件
		$default_config = new Zend_Config_Ini ( DATA_PATH . 'config.ini', null, array ('allowModifications' => 1 ) );
		
		$default_config->merge ( $application_config );
		
		self::$registry->config = $default_config;
		
		// 设置数据字典
		self::$registry->DictionaryINI = new Zend_Config_Ini ( DATA_PATH . 'dictionary.ini', null, array ('allowModifications' => 1 ) );
	}
	
	/**
	 * 设置默认时区
	 */
	public static function setupDateTime() {
		date_default_timezone_set ( self::$registry->config->general->timezone );
		Zend_Locale::setDefault ( 'zh_CN' );
	}
	
	/**
	 * 设置控制器
	 */
	public static function setupFrontController() {
		self::$frontController = Zend_Controller_Front::getInstance ();
		self::$frontController->throwExceptions ( self::$registry->config->general->show_error );
		
		$application_routes = require_once (APP_PATH . 'routes.php');
		$routers = self::$frontController->getRouter (); // 获取路由
		$routers->addRoutes ( $application_routes ['route_reg'] );
		self::$frontController->setControllerDirectory ( $application_routes ['controller_directory'] );
	}
	
	/**
	 * 设置视图
	 */
	public static function setupView() {
		if (self::$application == 'api') {
		
		} else {
			// 加载Smarty模板设置文件
			require_once (LIB_PATH . 'Cms/Templates.php');
			
			$view = new Smarty_Config ( self::$registry->config->smarty->toArray () );
			$view->setTemplateDir ( APP_PATH . self::$registry->config->smarty->template_dir );
			$view->setCompileDir ( APP_CACHE_PATH . self::$registry->config->smarty->compile_dir );
			$view->setCacheDir ( APP_CACHE_PATH . self::$registry->config->smarty->cache_dir );
			$view->_smarty->caching = self::$registry->config->smarty->caching; // 缓存设置
			                                                                    
			// 设置smarty的环境变量
			                                                                    // 用于视图页面输出
			                                                                    // {#siteJsPath#}等路径
			$view->_smarty->_config [0] ['vars'] = self::$registry->config->view_conf->toArray ();
			
			// 设置Smarty的扩展插件
			$view->_smarty->plugins_dir [] = LIB_PATH . "Cms/SmartyPluginsExt";
			
			// 设置Smarty的扩展函数
			require_once LIB_PATH . "Cms/SmartyFunctionsExt.php";
			$view->_smarty->register_function ( "zfCutstr", 'smartyCutstr' );
			$view->_smarty->register_function ( "heighKeyword", "smartyHeighKeyword" );
			
			// 将Smarty注册为全局变量
			self::$registry->Smarty = $view;
			
			// 设置Smarty为ZendStudio的默认视图层
			$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer ( $view );
			$viewRenderer->setViewSuffix ( self::$registry->config->smarty->view_suffix );
			Zend_Controller_Action_HelperBroker::addHelper ( $viewRenderer );
		}
	}
	
	/**
	 * 设置数据库
	 */
	public static function setupDatabase() {
		$databases_conf = self::$registry->config->databases;
		
		// 多数据库
		if ($databases_conf->multi) {
			// 适配器配置
			$dbAdapters = array ();
			foreach ( $databases_conf as $config_name => $dbinfo ) {
				if (is_object ( $dbinfo )) {
					$dbAdapters [$config_name] = Zend_Db::factory ( $dbinfo->adapter, $dbinfo->config->toArray () );
					$dbAdapters [$config_name]->query ( 'SET NAMES ' . $dbinfo->config->charset );
					$dbAdapters [$config_name]->query ( "SET CHARACTER SET '" . $dbinfo->config->charset . "'" );
					if (( boolean ) $dbinfo->isdefault) {
						Cms_DbTable::setDefaultAdapter ( $dbAdapters [$config_name] );
						if (( boolean ) $dbinfo->searchdb_hs) {
							$dbAdapters [$config_name . "_search"] = Zend_Db::factory ( $dbinfo->bbs->adapter, $dbinfo->bbs->config->toArray () );
							$dbAdapters [$config_name . "_search"]->query ( 'SET NAMES ' . $dbinfo->bbs->config->charset );
							$dbAdapters [$config_name . "_search"]->query ( "SET CHARACTER SET '" . $dbinfo->config->charset . "'" );
						}
					}
				}
			}
			Cms_DbTable::setAdapters ( $dbAdapters );
		} else {
			// 单个数据库
			$database = Zend_Db::factory ( $databases_conf->app->adapter, $databases_conf->app->config->toArray () );
			$database->query ( "SET NAMES " . $databases_conf->app->config->charset );
			$database->query ( "SET CHARACTER SET '" . $databases_conf->app->config->charset . "'" );
			
			Cms_DbTable::setDefaultAdapter ( $database );
		}
	}
	
	/**
	 * 设置Memcache缓存
	 */
	public static function setupMemcache() {
		$memcache = new Zend_Cache_Backend_Memcached ( array ('servers' => self::$registry->config->memcache->toArray (), 'compression' => true ) );
		self::$registry->MemCache = $memcache;
	}
	
	/**
	 * 设置存储缓存文件
	 */
	public static function setupCache() {
		$frontendOptions = array ('lifetime' => self::$registry->config->cache->lifetime, 'debug_header' => self::$registry->config->cache->debug_header );
		$backendOptions = array ('cache_dir' => DATA_PATH . self::$registry->config->cache->cache_dir );
		$cache = Zend_Cache::factory ( 'Core', 'File', $frontendOptions, $backendOptions );
		self::$registry->Cache = $cache;
	}
	
	/**
	 * 设置Zend Session
	 */
	public static function setupSession() {
		if (self::$application == 'admin') {
			$cms_AdminSession = Cms_AdminSession::getInstance ();
			$cms_AdminSession->init ( self::$registry->config->admincookie->toArray () );
			self::$registry->CmsAdminSession = $cms_AdminSession;
			self::$registry->CmsAdminSessionInfo = $cms_AdminSession->session_info;
		} elseif (self::$application == 'www') {
			$cms_Session = Cms_Session::getInstance ();
			$cms_Session->init ( self::$registry->config->cookie->toArray () );
			self::$registry->CmsSession = $cms_Session;
			self::$registry->CmsSessionInfo = $cms_Session->session_info;
		} else {
			// api
			if ($_SERVER ['REQUEST_URI'] == '/admin/login' || stristr ( $_SERVER ['REQUEST_URI'], '/admin/imgcode' )) {
				// 后台登陆 后台验证码显示
				$cms_AdminSession = Cms_AdminSession::getInstance ();
				$cms_AdminSession->init ( self::$registry->config->admincookie->toArray () );
				self::$registry->CmsAdminSession = $cms_AdminSession;
				self::$registry->CmsAdminSessionInfo = $cms_AdminSession->session_info;
			} else {
				$cms_Session = Cms_Session::getInstance ();
				$cms_Session->init ( self::$registry->config->cookie->toArray () );
				self::$registry->CmsSession = $cms_Session;
				self::$registry->CmsSessionInfo = $cms_Session->session_info;
			}
		}
	}
	
	/**
	 * 运行
	 */
	public function run() {
		self::$frontController->dispatch ();
	}
}
?>